using System;
using System.Data;
using System.Reflection;

namespace DataAccess
{
    /// <summary>
    /// Mapea un DataRow a su correspondiente entidad y vice-versa
    /// </summary>
    public static class EntityDataMapper
    {
        public static void MapToRow<T>(T entity, DataRow row)
        {
            Type type = entity.GetType();
            PropertyInfo[] props = type.GetProperties();
            object newValue;
            foreach (PropertyInfo prop in props)
            {
                if (row.Table.Columns.Contains(prop.Name))
                {
                    newValue = prop.GetValue(entity, null);
                    row[prop.Name] = newValue;
                }
            }
        }

        public static T MapToEntity<T>(DataRow row) where T : new()
        {
            T entity = new T();
            Type type = entity.GetType();
            PropertyInfo[] props = type.GetProperties();
            object newValue;
            foreach (PropertyInfo prop in props)
            {
                if (row.Table.Columns.Contains(prop.Name))
                {
                    newValue = row[prop.Name];
                    if (!Convert.IsDBNull(newValue))
                    {
                        prop.SetValue(entity, newValue, null);
                    }
                }
            }
            return entity;
        }
    }
}
